﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.RobotTracking.CApRTRobotTrackingModeMgr
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using EngineeringInternalExtension;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Resources;
using System.Windows.Forms;
using Tecnomatix.Engineering;


namespace DnProcessSimulateCommands.RobotTracking;

internal class CApRTRobotTrackingModeMgr
{
  private bool m_registeredForActiveDocumentUnloadingEvent;
  private CCoRTRobotTrackingToggleCmd m_cmd;
  private bool m_registeredForSimulationEvents;
  private bool m_isCmdDisabledInSilentSimulation;
  private bool m_isCmdToggledBeforeDissable;
  private bool m_registeredForTrackingSetEvents;
  private Dictionary<string, CApRTRobotTrackingSetInfo> m_observedTrackingSets = new Dictionary<string, CApRTRobotTrackingSetInfo>();

  internal CApRTRobotTrackingModeMgr(CCoRTRobotTrackingToggleCmd cmd) => this.m_cmd = cmd;

  internal void ActivateRobotTracking(bool activate)
  {
    TxApplicationEx.RobotTracker().ActivateTrackingMode(activate);
  }

  public void Init()
  {
    this.RegisterDocumentEvents();
    this.RegisterSimulationEvents(true);
    this.RegisterTrackingSetEvents();
  }

  public void Uninit()
  {
    this.UnregisterDocumentEvents();
    this.RegisterSimulationEvents(false);
    if (this.m_isCmdDisabledInSilentSimulation)
    {
      this.m_isCmdDisabledInSilentSimulation = false;
      this.m_cmd.ShouldEnable = true;
    }
    this.UnRegisterTrackingSetEvents();
  }

  private void RegisterDocumentEvents()
  {
    this.RegisterDocumentLoadedEvent();
    this.RegisterActiveDocumentUnLoadingEvent();
  }

  private void UnregisterDocumentEvents()
  {
    this.UnRegisterDocumentLoadedEvent();
    this.UnRegisterActiveDocumentUnLoadingEvent();
  }

  private void RegisterDocumentLoadedEvent()
  {
    TxApplication.DocumentCollection.DocumentLoaded += new TxDocumentCollection_DocumentLoadedEventHandler(this.OnLoadDocument);
  }

  private void UnRegisterDocumentLoadedEvent()
  {
    TxApplication.DocumentCollection.DocumentLoaded -= new TxDocumentCollection_DocumentLoadedEventHandler(this.OnLoadDocument);
  }

  private void RegisterActiveDocumentUnLoadingEvent()
  {
    if (this.m_registeredForActiveDocumentUnloadingEvent)
      return;
    TxDocument activeDocument = TxApplication.ActiveDocument;
    if (activeDocument == null || !TxApplication.ActiveDocument.PlatformGlobalServicesProvider.IsDocumentLoaded())
      return;
    activeDocument.Unloading += new TxDocument_UnloadingEventHandler(this.OnUnloadingDocument);
    this.m_registeredForActiveDocumentUnloadingEvent = true;
  }

  private void UnRegisterActiveDocumentUnLoadingEvent()
  {
    if (!this.m_registeredForActiveDocumentUnloadingEvent)
      return;
    this.m_registeredForActiveDocumentUnloadingEvent = false;
    TxDocument activeDocument = TxApplication.ActiveDocument;
    if (activeDocument == null)
      return;
    activeDocument.Unloading -= new TxDocument_UnloadingEventHandler(this.OnUnloadingDocument);
  }

  private void OnLoadDocument(object sender, TxDocumentCollection_DocumentLoadedEventArgs args)
  {
    this.RegisterActiveDocumentUnLoadingEvent();
    this.RegisterSimulationEvents(true);
    this.RegisterTrackingSetEvents();
  }

  private void OnUnloadingDocument(object sender, TxDocument_UnloadingEventArgs args)
  {
    this.UnRegisterActiveDocumentUnLoadingEvent();
    this.RegisterSimulationEvents(false);
    if (this.m_isCmdDisabledInSilentSimulation)
    {
      this.m_isCmdDisabledInSilentSimulation = false;
      this.m_cmd.ShouldEnable = true;
    }
    this.UnRegisterTrackingSetEvents();
    this.ActivateRobotTracking(false);
    if (!this.m_cmd.Pressed)
      return;
    this.m_cmd.Pressed = false;
    new TxCommandManager().NotifyCommandExecuted((ITxCommand) this.m_cmd);
  }

  private void RegisterSimulationEvents(bool register)
  {
    try
    {
      TxDocument activeDocument = TxApplication.ActiveDocument;
      if (activeDocument == null)
        return;
      if (register)
      {
        if (this.m_registeredForSimulationEvents || !TxApplication.ActiveDocument.PlatformGlobalServicesProvider.IsDocumentLoaded())
          return;
        this.m_registeredForSimulationEvents = true;
        activeDocument.SimulationPlayer.SimulationStartedForward += new TxSimulationPlayer_SimulationStartedForwardEventHandler(this.SimulationPlayer_SimulationStartedForward);
        activeDocument.SimulationPlayer.SimulationStartedBackward += new TxSimulationPlayer_SimulationStartedBackwardEventHandler(this.SimulationPlayer_SimulationStartedBackward);
        activeDocument.SimulationPlayer.SimulationStopped += new TxSimulationPlayer_SimulationStoppedEventHandler(this.SimulationPlayer_SimulationStopped);
        activeDocument.SimulationPlayer.SimulationEndedForward += new TxSimulationPlayer_SimulationEndedForwardEventHandler(this.SimulationPlayer_SimulationEndedForward);
        activeDocument.SimulationPlayer.SimulationEndedBackward += new TxSimulationPlayer_SimulationEndedBackwardEventHandler(this.SimulationPlayer_SimulationEndedBackward);
      }
      else
      {
        if (!this.m_registeredForSimulationEvents)
          return;
        this.m_registeredForSimulationEvents = false;
        activeDocument.SimulationPlayer.SimulationStartedForward -= new TxSimulationPlayer_SimulationStartedForwardEventHandler(this.SimulationPlayer_SimulationStartedForward);
        activeDocument.SimulationPlayer.SimulationStartedBackward -= new TxSimulationPlayer_SimulationStartedBackwardEventHandler(this.SimulationPlayer_SimulationStartedBackward);
        activeDocument.SimulationPlayer.SimulationStopped -= new TxSimulationPlayer_SimulationStoppedEventHandler(this.SimulationPlayer_SimulationStopped);
        activeDocument.SimulationPlayer.SimulationEndedForward -= new TxSimulationPlayer_SimulationEndedForwardEventHandler(this.SimulationPlayer_SimulationEndedForward);
        activeDocument.SimulationPlayer.SimulationEndedBackward -= new TxSimulationPlayer_SimulationEndedBackwardEventHandler(this.SimulationPlayer_SimulationEndedBackward);
      }
    }
    catch (Exception ex)
    {
    }
  }

  private void SimulationPlayer_SimulationStartedForward(
    object sender,
    TxSimulationPlayer_SimulationStartedForwardEventArgs e)
  {
    this.HandleSimulationStarted();
  }

  private void SimulationPlayer_SimulationStartedBackward(
    object sender,
    TxSimulationPlayer_SimulationStartedBackwardEventArgs e)
  {
    this.HandleSimulationStarted();
  }

  private void SimulationPlayer_SimulationStopped(
    object sender,
    TxSimulationPlayer_SimulationStoppedEventArgs e)
  {
    this.HandleSimulationStopped();
  }

  private void SimulationPlayer_SimulationEndedForward(
    object sender,
    TxSimulationPlayer_SimulationEndedForwardEventArgs e)
  {
    this.HandleSimulationStopped();
  }

  private void SimulationPlayer_SimulationEndedBackward(
    object sender,
    TxSimulationPlayer_SimulationEndedBackwardEventArgs e)
  {
    this.HandleSimulationStopped();
  }

  private void HandleSimulationStarted()
  {
    if (TxApplication.ActiveDocument.SimulationPlayer.RefreshMode || this.m_isCmdDisabledInSilentSimulation)
      return;
    if (((TxToggleButtonCommand) this.m_cmd).Push)
    {
      ((TxButtonCommand) this.m_cmd).Execute((object) null);
      this.m_isCmdToggledBeforeDissable = !((TxToggleButtonCommand) this.m_cmd).Push;
    }
    this.m_cmd.ShouldEnable = false;
    this.m_isCmdDisabledInSilentSimulation = true;
    TxApplicationEx.RobotTracker().FireTrackingModeEnablerChanged(new TxRobotTrackerEx_TrackingModeEnablerChangedEventArgs());
  }

  private void HandleSimulationStopped()
  {
    if (!this.m_isCmdDisabledInSilentSimulation)
      return;
    this.m_cmd.ShouldEnable = true;
    this.m_isCmdDisabledInSilentSimulation = false;
    if (this.m_isCmdToggledBeforeDissable)
    {
      this.m_isCmdToggledBeforeDissable = false;
      ((TxButtonCommand) this.m_cmd).Execute((object) null);
    }
    TxApplicationEx.RobotTracker().FireTrackingModeEnablerChanged(new TxRobotTrackerEx_TrackingModeEnablerChangedEventArgs());
  }

  private ResourceManager GetResourceManager()
  {
    return new ResourceManager("DnProcessSimulateCommands.RobotTracking.Res.ResourceTable", this.GetType().Assembly);
  }

  private void RegisterTrackingSetEvents()
  {
    if (this.m_registeredForTrackingSetEvents || !TxApplication.ActiveDocument.PlatformGlobalServicesProvider.IsDocumentLoaded())
      return;
    TxApplicationEx.RobotTracker().SetAdded += new TxRobotTrackerEx_SetAddedEventHandler(this.CApRTRobotTrackingModeMgr_SetAdded);
    TxApplicationEx.RobotTracker().SetDeleted += new TxRobotTrackerEx_SetDeletedEventHandler(this.CApRTRobotTrackingModeMgr_SetDeleted);
    this.RegisterToAllTrackingSets();
    this.m_registeredForTrackingSetEvents = true;
  }

  private void UnRegisterTrackingSetEvents()
  {
    if (!this.m_registeredForTrackingSetEvents)
      return;
    TxApplicationEx.RobotTracker().SetAdded -= new TxRobotTrackerEx_SetAddedEventHandler(this.CApRTRobotTrackingModeMgr_SetAdded);
    TxApplicationEx.RobotTracker().SetDeleted -= new TxRobotTrackerEx_SetDeletedEventHandler(this.CApRTRobotTrackingModeMgr_SetDeleted);
    this.UnRegisterToAllTrackingSets();
    this.m_registeredForTrackingSetEvents = false;
  }

  private void RegisterToAllTrackingSets()
  {
    ArrayList trackingSets = TxApplicationEx.RobotTracker().TrackingSets;
    if (trackingSets == null)
      return;
    foreach (TxRobotTrackingSetEx robotTrackingSetEx in trackingSets)
    {
      if (!this.m_observedTrackingSets.ContainsKey(robotTrackingSetEx.Id))
      {
        CApRTRobotTrackingSetInfo robotTrackingSetInfo = new CApRTRobotTrackingSetInfo(robotTrackingSetEx);
        this.m_observedTrackingSets.Add(robotTrackingSetEx.Id, robotTrackingSetInfo);
        this.RegisterToTrackingSetActivated(robotTrackingSetEx);
      }
    }
  }

  private void UnRegisterToAllTrackingSets()
  {
    foreach (CApRTRobotTrackingSetInfo robotTrackingSetInfo in this.m_observedTrackingSets.Values)
      this.UnRegisterToTrackingSetActivated(robotTrackingSetInfo.TrackingSet);
    this.m_observedTrackingSets.Clear();
  }

  private void RegisterToTrackingSetActivated(TxRobotTrackingSetEx trackingSet)
  {
    if (trackingSet == null || !this.m_observedTrackingSets.ContainsKey(trackingSet.Id))
      return;
    CApRTRobotTrackingSetInfo observedTrackingSet = this.m_observedTrackingSets[trackingSet.Id];
    CApRTRobotTrackingSetInfo.eObservedEventTypes observedEventTypes = CApRTRobotTrackingSetInfo.eObservedEventTypes.Activated;
    if ((observedTrackingSet.ObservedEvents & observedEventTypes) == observedEventTypes)
      return;
    trackingSet.Activated += new TxRobotTrackingSetEx_ActivatedEventHandler(this.trackingSet_Activated);
    observedTrackingSet.ObservedEvents |= observedEventTypes;
  }

  private void UnRegisterToTrackingSetActivated(TxRobotTrackingSetEx trackingSet)
  {
    if (trackingSet == null || !this.m_observedTrackingSets.ContainsKey(trackingSet.Id))
      return;
    CApRTRobotTrackingSetInfo observedTrackingSet = this.m_observedTrackingSets[trackingSet.Id];
    CApRTRobotTrackingSetInfo.eObservedEventTypes observedEventTypes = CApRTRobotTrackingSetInfo.eObservedEventTypes.Activated;
    if ((observedTrackingSet.ObservedEvents & observedEventTypes) != observedEventTypes)
      return;
    trackingSet.Activated -= new TxRobotTrackingSetEx_ActivatedEventHandler(this.trackingSet_Activated);
    observedTrackingSet.ObservedEvents &= ~observedEventTypes;
  }

  private void CApRTRobotTrackingModeMgr_SetAdded(TxRobotTrackerEx_SetAddedEventArgs e)
  {
    if (this.m_observedTrackingSets.ContainsKey(e.TrackingSet.Id))
      return;
    CApRTRobotTrackingSetInfo robotTrackingSetInfo = new CApRTRobotTrackingSetInfo(e.TrackingSet);
    this.m_observedTrackingSets.Add(e.TrackingSet.Id, robotTrackingSetInfo);
    this.RegisterToTrackingSetActivated(e.TrackingSet);
  }

  private void CApRTRobotTrackingModeMgr_SetDeleted(TxRobotTrackerEx_SetDeletedEventArgs e)
  {
    if (!this.m_observedTrackingSets.ContainsKey(e.TrackingSet.Id))
      return;
    this.UnRegisterToTrackingSetActivated(e.TrackingSet);
    this.m_observedTrackingSets.Remove(e.TrackingSet.Id);
  }

  private void trackingSet_Activated(TxRobotTrackingSetEx_ActivatedEventArgs e)
  {
    if (e.TrackingSet == null || e.TrackingSet.IsActive || e.ObserverParams != 1)
      return;
    ResourceManager resourceManager = this.GetResourceManager();
    string str1 = resourceManager.GetString("TITLE_ROBOT_TRACKING");
    string format = resourceManager.GetString("MSG_TRACKING_SET_ATTACHMENT_LOOP");
    string str2 = "";
    string str3 = "";
    bool flag = true;
    try
    {
      str2 = ((TxBaseGeometryCreationObject) e.TrackingSet.Data.Robot).Name;
      str3 = e.TrackingSet.Data.ReferenceFrame.Name;
    }
    catch
    {
      flag = false;
    }
    if (!flag)
      return;
    int num = (int) TxMessageBox.Show(string.Format(format, (object) str2, (object) str3), str1, MessageBoxButtons.OK, MessageBoxIcon.Hand);
  }

  private void VerifyActiveSetsAttachments()
  {
    List<CApRTRobotTrackingAttachmentPair> trackingAttachmentPairList1 = new List<CApRTRobotTrackingAttachmentPair>();
    ArrayList trackingSets = TxApplicationEx.RobotTracker().TrackingSets;
    if (trackingSets != null && trackingSets.Count > 0)
    {
      foreach (TxRobotTrackingSetEx robotTrackingSetEx in trackingSets)
      {
        if (robotTrackingSetEx != null && robotTrackingSetEx.IsActive)
        {
          TxRobotTrackingSetDataEx data = robotTrackingSetEx.Data;
          CApRTRobotTrackingAttachmentPair trackingAttachmentPair = new CApRTRobotTrackingAttachmentPair((ITxLocatableObject) data.ReferenceFrame, data.TrackedObject);
          trackingAttachmentPairList1.Add(trackingAttachmentPair);
        }
      }
    }
    List<CApRTRobotTrackingAttachmentPair> needAttachmentPairs = new List<CApRTRobotTrackingAttachmentPair>();
    foreach (CApRTRobotTrackingAttachmentPair trackingAttachmentPair in trackingAttachmentPairList1)
    {
      if (trackingAttachmentPair.NeedToAttach())
        needAttachmentPairs.Add(trackingAttachmentPair);
    }
    DialogResult dlgResult = DialogResult.Ignore;
    if (needAttachmentPairs.Count <= 0 || !this.ShowAttachFramesToObjectsForm(needAttachmentPairs, out dlgResult) || dlgResult != DialogResult.Yes)
      return;
    List<CApRTRobotTrackingAttachmentPair> trackingAttachmentPairList2 = new List<CApRTRobotTrackingAttachmentPair>();
    foreach (CApRTRobotTrackingAttachmentPair trackingAttachmentPair in needAttachmentPairs)
    {
      if (!trackingAttachmentPair.TryAttach())
        trackingAttachmentPairList2.Add(trackingAttachmentPair);
    }
    if (trackingAttachmentPairList2.Count <= 0)
      return;
    ResourceManager resourceManager = this.GetResourceManager();
    string str1 = resourceManager.GetString("ERROR_CAPTION");
    string str2 = resourceManager.GetString("MSG_FAIL_TO_ATTACH");
    string format = resourceManager.GetString("FORMAT_ATTACH_FRAMES_TO_OBJECTS_LISTING");
    bool flag = true;
    try
    {
      foreach (CApRTRobotTrackingAttachmentPair trackingAttachmentPair in trackingAttachmentPairList2)
      {
        string str3 = string.Format(format, (object) ((ITxObject) trackingAttachmentPair.ObjectToAttach).Name, (object) ((ITxObject) trackingAttachmentPair.AttachmentParentCandidate).Name);
        str2 = $"{str2}\r\n{str3}";
      }
    }
    catch (Exception ex)
    {
      flag = false;
    }
    if (!flag)
      return;
    int num = (int) TxMessageBox.Show(str2, str1, MessageBoxButtons.OK, MessageBoxIcon.Hand);
  }

  private bool ShowAttachFramesToObjectsForm(
    List<CApRTRobotTrackingAttachmentPair> needAttachmentPairs,
    out DialogResult dlgResult)
  {
    dlgResult = DialogResult.Ignore;
    bool objectsForm;
    try
    {
      CUiRTAttachFramesToObjectsForm framesToObjectsForm = new CUiRTAttachFramesToObjectsForm();
      objectsForm = framesToObjectsForm.FillAttachmentPairs(needAttachmentPairs);
      if (objectsForm)
      {
        framesToObjectsForm.AutoSizeControlsHeight();
        dlgResult = ((Form) framesToObjectsForm).ShowDialog();
      }
    }
    catch (Exception ex)
    {
      objectsForm = false;
    }
    return objectsForm;
  }
}
